<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active {
      color: red;
    }
  </style>
</head>

<body>
  <div id="app">
    <router-link tag="button" to="/home">到首页</router-link>
    <router-link tag="button" to="/news">到新闻</router-link>
    <router-link tag="button" to="/about">到关于我们</router-link>
    <hr>
    <!-- 视图上定义 路由组件出口 -->
    <router-view></router-view>
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // 第一步 组件 路由组件的 options 
    const Home = {
      template: `
        <div>
          <h2>首页</h2>  
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h2>新闻页</h2>  
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h2>关于我们页</h2>  
        </div>
      `
    }
    // 定义404组件 路由 options
    const NotFound = {
      template: `
        <div>
          <h2>404啦</h2>  
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h2>登录页</h2>  
          <button @click="doLogin">登录</button>
        </div>
      `,
      methods: {
        doLogin() {
          setTimeout(() => {

            const token = 'fergr394grhvfd';
            // 立即缓存起来
            localStorage.setItem('token', token);
            // 回到关于我们
            this.$router.replace('/home');
          }, 1000)
        }
      }
    }
    // 定义路由 router 实例对象
    const routes = [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        name: '首页',
        component: Home
      },
      {
        path: '/news',
        name: '新闻',
        component: News
      },
      {
        path: '/about',
        name: '关于我们',
        component: About
      },
      {
        path: '/login',
        name: '登录',
        component: Login
      },
      {
        path: '*',
        component: NotFound
      }
    ]
    const router = new VueRouter({
      routes
    })
    // 全局前置守卫
    router.beforeEach((to, from, next) => {
      // 判断是否是登录页或者注册页 是 无条件放行
      const noAuthPath = ['/login', '/register'];
      if (noAuthPath.includes(to.path)) {
        next();
      } else {
        const token = localStorage.getItem('token');
        if (token) {
          next();
        } else {
          next('/login')
        }
      }

    })
    const vm = new Vue({
      el: '#app',
      router
    })
  </script>
</body>

</html>